package com.chinackts.customsdeclarations.repository.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Slf4j
@Repository
public class DecDetailLastReqTimeRepository {

    @Resource
    private StringRedisTemplate redisTemplate1;

    private static final String KEY = "cus-dec-last-req:%s";

    @Value("${e-port.redis.cus-dec-timeout:6000}")
    private long timeout;


    /**
     * 获取剩余时间
     * @param socialCreditCode 企业组织机构代码
     */
    public long getRemainingTime(String socialCreditCode) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        String time = ops.get(String.format(KEY, socialCreditCode));
        if (StringUtils.isEmpty(time)) {
            log.warn("未缓存关单明细请求时间，则为首次请求: {}，剩余 0 ms", socialCreditCode);
            return 0L;
        }
        long last = Long.parseLong(time);
        long current = System.currentTimeMillis();
        long remainingTime = last + timeout - current;
        return Math.max(remainingTime, 0L);
    }

    /**
     * 存储当前时间
     * @param socialCreditCode 企业组织机构代码
     */
    public long saveCurrentTime(String socialCreditCode) {
        ValueOperations<String, String> ops = this.redisTemplate1.opsForValue();
        long currentTimeMillis = System.currentTimeMillis();
        ops.set(String.format(KEY, socialCreditCode), String.valueOf(currentTimeMillis));
        return currentTimeMillis;
    }

}
